package com.atguigu.ssyx.home.service.impl;

import com.atguigu.ssyx.client.activity.ActivityFeignClient;
import com.atguigu.ssyx.client.product.ProductFeignClient;
import com.atguigu.ssyx.client.search.SearchFeignClient;
import com.atguigu.ssyx.home.service.ItemService;
import com.atguigu.ssyx.model.product.SkuInfo;
import com.atguigu.ssyx.vo.product.SkuInfoVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;


@Service
@RequiredArgsConstructor
public class ItemServiceImpl implements ItemService {
    private final ProductFeignClient productFeignClient;
    private final ActivityFeignClient activityFeignClient;
    private final SearchFeignClient searchFeignClient;

    private final ThreadPoolExecutor threadPoolExecutor;

    @Override
    public Map<String, Object> getItemInfo(Long SkuId, Long userId) {
        HashMap<String, Object> result = new HashMap<>();
        //1.根据SkuId查询SkuInfoVo信息
        CompletableFuture<Void> skuInfoCompletableFuture = CompletableFuture.runAsync(() -> {
            //远程调用service-product服务，查询SkuInfoVo信息
            SkuInfoVo skuInfoVo = productFeignClient.getSkuInfoVo(SkuId);
            result.put("skuInfoVo", skuInfoVo);
        }, threadPoolExecutor);


        //2.获取Sku对应优惠卷信息
        CompletableFuture<Void> activityAmdCouponFuture = CompletableFuture.runAsync(() -> {
            //远程调用service-activity服务，查询优惠卷信息
            Map<String, Object> activityAndCoupon = activityFeignClient.findActivityAndCoupon(SkuId, userId);
            result.put("activityAmdCoupon", activityAndCoupon);
        }, threadPoolExecutor);

        //3.更新商品热度

        CompletableFuture<Void> hotFuture = CompletableFuture.runAsync(() -> {
            //远程调用service-service服务，使得商品热度+1
            searchFeignClient.updateHotSku(SkuId);

        }, threadPoolExecutor);

        //4.等待所有异步任务执行完成
        CompletableFuture.allOf
                        (skuInfoCompletableFuture,
                                activityAmdCouponFuture,
                                hotFuture)
                .join();

        return result;
    }


}
